import logging
import os
from logging import handlers



def _logging(**kwargs):
    level = kwargs.pop('level', None)
    filename = kwargs.pop('filename', None)
    datefmt = kwargs.pop('datefmt', None)
    log_format = kwargs.pop('format', None)  # 避免与内置函数format冲突，重命名变量
    when = kwargs.pop('when', 'D')  # 添加切割周期参数，默认按天切割
    interval = kwargs.pop('interval', 1)  # 切割间隔，默认1

    if level is None:
        level = logging.DEBUG
    if filename is None:
        filename = 'default.log'
    if datefmt is None:
        datefmt = '%Y-%m-%d %H:%M:%S'
    if log_format is None:
        log_format = '%(asctime)s [%(module)s] %(levelname)s [%(lineno)d] %(message)s'

    log = logging.getLogger(filename)
    # 避免重复添加handler
    if log.hasHandlers():
        log.handlers.clear()

    format_str = logging.Formatter(log_format, datefmt)

    # 创建日志目录
    log_dir = os.path.dirname(filename) or './logs'
    os.makedirs(log_dir, exist_ok=True)
    debug_log_dir = './debug/logs'
    os.makedirs(debug_log_dir, exist_ok=True)

    # DEBUG级别日志处理器（输出到debug目录）
    th_debug = handlers.TimedRotatingFileHandler(
        filename=os.path.join(debug_log_dir, os.path.basename(filename)),
        when=when,
        interval=interval,
        backupCount=3,
        encoding='utf-8'
    )
    th_debug.setFormatter(format_str)
    th_debug.setLevel(logging.DEBUG)
    log.addHandler(th_debug)

    # INFO级别日志处理器（输出到主日志目录）
    th = handlers.TimedRotatingFileHandler(
        filename=filename,
        when=when,
        interval=interval,
        backupCount=3,
        encoding='utf-8'
    )
    th.setFormatter(format_str)
    th.setLevel(logging.INFO)
    log.addHandler(th)

    log.setLevel(level)
    return log


# # 使用示例：
# # 1. 按天切割（默认）
# logger_day = _logging(filename='./logs/app_day.log')
#
# # 2. 按小时切割
# logger_hour = _logging(filename='./logs/app_hour.log', when='H')
#
# # 3. 按分钟切割
# logger_minute = _logging(filename='./logs/app_minute.log', when='M')
#
# # 4. 按周切割（注意：周切割的interval必须是1）
# logger_week = _logging(filename='./logs/app_week.log', when='W0')  # W0表示周一为一周的开始

